<template>
  <div>
    <Category :scene="scene"></Category>
    <!-- 平台属性 -->
    <el-card
      shadow="always"
      :body-style="{ padding: '20px' }"
      style="margin: 20px 0"
    >
      <!-- card body -->
      <!-- 平台属性页面 -->
      <div v-show="scene == 0">
        <!-- 当未拿到三级分类的id时,禁用添加属性按钮 -->
        <el-button
          type="primary"
          size="default"
          :icon="Plus"
          @click="addAttr"
          :disabled="!categoryStore.c3Id"
          >添加属性</el-button
        >
        <el-table border :data="attrList" style="margin: 20px 0">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="品牌属性"
            prop="attrName"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-tag
                type="success"
                size="small"
                v-for="(attrVal, index) in row.attrValueList"
                :key="attrVal.id"
                >{{ attrVal.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click="updateAttr(row)"
              ></el-button>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="deleteAttr(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 平台属性值页面 -->
      <div v-show="scene == 1">
        <el-form :inline="true">
          <el-form-item label="属性名">
            <!-- 双向绑定属性名 -->
            <el-input v-model="attrParams.attrName" clearable></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          :icon="Plus"
          :disabled="attrParams.attrName == '' ? true : false"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button @click="cancel">取消</el-button>
        <el-table
          border
          style="margin: 20px 0"
          :data="attrParams.attrValueList"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          >
          </el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <!-- 编辑页面 -->
              <el-input
                :ref="(vc) => (inputArr[$index] = vc)"
                placeholder="请输入属性值"
                size="small"
                clearable
                v-model="row.valueName"
                @blur="toLook(row, $index)"
                v-if="row.flag"
              ></el-input>
              <!-- 查看页面 -->
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button type="danger" size="small" :icon="Delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
          @click="saveAttr"
          >保存</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
// 引入小图标
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
} from "@element-plus/icons-vue";
import useCategoryStore from "@/stores/category";
import { watch, ref, reactive, nextTick, onUnmounted } from "vue";
import {
  reqAttrList,
  reqAttrValueList,
  reqDeleteAttr,
} from "@/api/product/attr/attr";
import { ElMessage } from "element-plus";
let categoryStore = useCategoryStore();
// 存储平台属性
let attrList = ref([]);
// 定义切换场景的变量
let scene = ref(0);
// 定义未来要给服务器传递的数据
let attrParams = reactive({
  attrName: "", //属性名
  attrValueList: [], //属性值数组
  categoryId: "", //三级目录的id
  categoryLevel: 3, //三级目录
});
// 定义el-input的响应式数据,拿到el-input的实例
let inputArr = ref([]);
watch(
  () => categoryStore.c3Id,
  () => {
    getAttrList();
  }
);

const getAttrList = async () => {
  let result = await reqAttrList(
    categoryStore.c1Id,
    categoryStore.c2Id,
    categoryStore.c3Id
  );
  console.log(result);
  attrList.value = result;
};
// 添加属性按钮跳转到平台属性值页面
const addAttr = () => {
  // 切换场景
  scene.value = 1;
  Object.assign(attrParams, {
    attrName: "", //属性名
    attrValueList: [], //属性值数组
    categoryId: categoryStore.c3Id, //三级目录的id
    categoryLevel: 3, //三级目录
  });
};

// 添加属性值按钮的回调
const addAttrValue = () => {
  // 当数组中有值的时候表格中添加一行,所以还要在页面中使用插槽来显示结构
  attrParams.attrValueList.push({
    // 属性值
    valueName: "",
    // 将flag设置在数组对象中,达到一个flag控制一条对象的目的
    flag: true,
  });
  nextTick(() => {
    // 通过数组长度来实现聚焦
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};

// 编辑模式失去焦点变为查看模式
const toLook = (row, $index) => {
  // 当文本框中值为空时,不能转为查看模式
  if (row.valueName.trim() == "") {
    // 弹出警告信息
    ElMessage({
      type: "warning",
      message: "属性值不能为空",
      duration: 500,
    });
    // 并删除这条空数据
    attrParams.attrValueList.splice($index, 1);
    return;
  }
  // 当文本框中出现相同数据时,需要删除重复的数据
  let repeated = attrParams.attrValueList.find((item) => {
    // 首先得排除自身,即判断两个对象是否相同
    if (row != item) {
      return (row.valueName = item.valueName);
    }
  });
  // 如果有重复的,则
  if (repeated) {
    ElMessage({
      type: "warning",
      message: `属性值${row.valueName}重复`,
    });
    // 删除重复数据
    attrParams.attrValueList.splice($index, 1);
  }

  row.flag = false;
};
// 点击查看模式切换为编辑模式
const toEdit = (row, $index) => {
  row.flag = true;
  // 从查看模式转换为编辑模式时,需要聚焦,注意顺序问题
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};

// 点击取消
const cancel = () => {
  // 切换场景
  scene.value = 0;
};

// 点击保存
const saveAttr = async () => {
  // 整理数据,传递给服务器的数据不要flag
  attrParams.attrValueList.forEach((item) => {
    if (item.hasOwnProperty("flag")) {
      delete item.flag;
    }
  });
  try {
    // 发请求
    await reqAttrValueList(attrParams);
    // 切换场景
    scene.value = 0;
    // 提示信息
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改数据成功" : "添加数据成功",
    });
    // 再次发请求
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "error",
      message: attrParams.id ? "修改数据失败" : "添加数据失败",
    });
  }
};
// 修改按钮修改属性值
const updateAttr = (row) => {
  // 切换场景
  scene.value = 1;
  // 深拷贝
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
};

// 删除按钮删除平台属性
const deleteAttr = async (row) => {
  try {
    await reqDeleteAttr(row.id);
    // 提示信息
    ElMessage({
      type: "success",
      message: "删除数据成功",
    });
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "error",
      message: "删除数据失败",
    });
  }
};
// 组件卸载时清空三级联动中的数据,即清空他们在仓库中的id和列表
onUnmounted(() => {
  // 清空id
  categoryStore.c1Id = "";
  categoryStore.c2Id = "";
  categoryStore.c3Id = "";
  // 清空列表
  categoryStore.c1List = [];
  categoryStore.c2List = [];
  categoryStore.c3List = [];
});
</script>

<style scoped>
</style>